﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DatabaseInterface
{
    public partial class ConfigureConnection : Form
    {
        private Connection cnx;
        private XMLData.XMLData xmlData;
        public ConfigureConnection()
        {
            InitializeComponent();
            this.xmlData = new XMLData.XMLData();
        }

        private void ConfigureConnection_Load(object sender, EventArgs e)
        {
            //LoadSQLInstances();
            //SqlConnection cnx = new SqlConnection(Properties.Settings.Default.CarbonTrackerConnectionString);
            try
            {
                this.cnx = new Connection();
                cmbSqlServers.Text = cnx.DataSource;
                txtPassword.Text = cnx.Password;
                txtUsername.Text = cnx.User;
                cmdDatabases.Text = cnx.Catalog;
                chkWindowsAuth.Checked = cnx.WindowsAuth;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void LoadSQLInstances()
        {
            //this.sqlExpressCombo1.Refresh_List();
            System.Data.Sql.SqlDataSourceEnumerator en = System.Data.Sql.SqlDataSourceEnumerator.Instance;
            DataTable t = en.GetDataSources();
            foreach (DataRow r in t.Rows)
            {
                cmbSqlServers.Items.Add(r[0].ToString() + @"\" + r[1].ToString());
            }
        }

        private void cmdDatabases_DropDown(object sender, EventArgs e)
        {
            cmdDatabases.Items.Clear();
            try
            {
                //System.Data.SqlClient.SqlConnection cnx = new System.Data.SqlClient.SqlConnection();
                //cnx.ConnectionString = "Data Source=" + cmbSqlServers.Text + ";User ID=" + txtUsername.Text + ";Password=" + txtPassword.Text;
                System.Data.SqlClient.SqlConnection cnx = BuildTmpConnection();
                cnx.Open();
                DataTable catalogTable = cnx.GetSchema("Databases");
                cnx.Close();

                foreach (DataRow row in catalogTable.Rows)
                {
                    cmdDatabases.Items.Add(row[0].ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void sqlExpressCombo1_DropDown(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.cnx.User = txtUsername.Text;
            this.cnx.Password = txtPassword.Text;
            this.cnx.Catalog = cmdDatabases.Text;
            this.cnx.DataSource = cmbSqlServers.Text;
            this.cnx.WindowsAuth = chkWindowsAuth.Checked;
            this.cnx.Save();

            this.Close();
        }
        private SqlConnection BuildTmpConnection()
        {
            SqlConnectionStringBuilder cnxBuilder = new SqlConnectionStringBuilder();
            if (chkWindowsAuth.Checked)
            {
                cnxBuilder.IntegratedSecurity = true;
            }
            else
            {
                cnxBuilder.UserID = txtUsername.Text;
                cnxBuilder.Password = txtPassword.Text;
            }
            cnxBuilder.InitialCatalog = cmdDatabases.Text;
            cnxBuilder.DataSource = cmbSqlServers.Text;
            SqlConnection connection = new SqlConnection(cnxBuilder.ConnectionString);
            return connection;
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            SqlConnection connection = BuildTmpConnection();
            SqlCommand cmd = new SqlCommand("SELECT getdate()", connection);
            SqlDataReader dr;
            try
            {
                connection.Open();
                dr = cmd.ExecuteReader();
                if (!dr.HasRows)
                {
                    throw new Exception();
                }
                else
                {
                    MessageBox.Show("Connection Successful", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                connection.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("SQL Server Connection Failed\r" + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                }
            }
        }

        private void chkWindowsAuth_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chkWindowsAuth.Checked)
            {
                this.txtPassword.Enabled = false;
                this.txtUsername.Enabled = false;
            }
            else
            {
                this.txtPassword.Enabled = true;
                this.txtUsername.Enabled = true;
            }
        }
        private void cmbSqlServers_DropDown(object sender, EventArgs e)
        {
            LoadSQLInstances();
        }
    }
}
